<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>订单管理</title>
    <link rel="stylesheet" href="static/elementui.css">
    <script src="static/vue@2.6.14.js"></script>
    <script src="static/elementui.js"></script>
    <script src="static/axios.min.js"></script>
    <style>
        body {
            padding: 20px;
        }

        .toolbar {
            margin-bottom: 20px;
        }

        .dialog-footer {
            text-align: right;
            margin-top: 20px;
        }

        .el-table .el-button {
            margin-bottom: 10px;
        }

        .ticket-dialog {
            text-align: center;
        }

        .ticket-content {
            padding: 20px;
            border: 2px dashed #dcdfe6;
            margin: 10px;
            background-color: #f5f7fa;
        }

        .ticket-header {
            font-size: 24px;
            margin-bottom: 20px;
            color: #303133;
        }

        .ticket-info {
            text-align: left;
            margin: 10px 0;
            line-height: 1.8;
        }
    </style>
</head>
<body>
<div id="app">
    <el-card>
        <div class="toolbar">
            <el-input placeholder="搜索订单编号" v-model="searchKeyword" style="width: 200px;"></el-input>
            <el-button type="primary" size="small" @click="fetchOrders">搜索</el-button>
        </div>
        <el-table :data="orders" stripe>
            <el-table-column prop="id" label="订单ID"></el-table-column>
            <el-table-column prop="userFullname" label="用户姓名"></el-table-column>
            <el-table-column prop="movieTitle" label="电影名称"></el-table-column>
            <el-table-column prop="cinemaName" label="影院名称"></el-table-column> <!-- 新增影院名称列 -->
<%--            <el-table-column prop="showtimeId" label="场次ID"></el-table-column>--%>
            <el-table-column prop="seats" label="座位">
                <template slot-scope="scope">
                    <span>{{ scope.row.seats.join(', ') }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="totalPrice" label="总价"></el-table-column>
            <el-table-column prop="orderTime" label="下单时间"></el-table-column>
            <el-table-column prop="status" label="状态">
                <template slot-scope="scope">
                    <span>{{ scope.row.status.paymentStatus }}</span>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="280">
                <template slot-scope="scope">
                    <el-button @click="handleDelete(scope.row)" type="danger" size="small">删除</el-button>
                    <el-button v-if="scope.row.status.paymentStatus === 'pending'"
                               @click="handlePay(scope.row)"
                               type="success"
                               size="small">支付</el-button>
                    <el-button v-if="scope.row.status.paymentStatus === 'paid'"
                               @click="showTicket(scope.row)"
                               type="primary"
                               size="small">打印票据</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="block">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 20, 50]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalOrders">
            </el-pagination>
        </div>

        <!-- 票据对话框 -->
        <el-dialog
                title="电影票据"
                :visible.sync="ticketDialogVisible"
                width="500px"
                class="ticket-dialog">
            <div class="ticket-content">
                <div class="ticket-header">
                    <i class="el-icon-ticket"></i> 电影票据
                </div>
                <div class="ticket-info" v-if="selectedOrder">
                    <p><strong>订单编号：</strong>{{ selectedOrder.id }}</p>
                    <p><strong>用户姓名：</strong>{{ selectedOrder.userFullname }}</p>
                    <p><strong>电影名称：</strong>{{ selectedOrder.movieTitle }}</p>
                    <p><strong>影院名称：</strong>{{ selectedOrder.cinemaName }}</p> <!-- 新增影院名称 -->
<%--                    <p><strong>场次ID：</strong>{{ selectedOrder.showtimeId }}</p>--%>
                    <p><strong>座位：</strong>{{ selectedOrder.seats.join(', ') }}</p>
                    <p><strong>总价：</strong>￥{{ selectedOrder.totalPrice }}</p>
                    <p><strong>下单时间：</strong>{{ selectedOrder.orderTime }}</p>
                    <p><strong>支付状态：</strong>已支付</p>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="printTicket" type="primary">打印</el-button>
                <el-button @click="ticketDialogVisible = false">关闭</el-button>
            </span>
        </el-dialog>
    </el-card>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                searchKeyword: '',
                orders: [],
                totalOrders: 0,
                pageSize: 5,
                currentPage: 1,
                user: null,
                ticketDialogVisible: false,
                selectedOrder: null
            };
        },
        watch: {
            searchKeyword(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.currentPage = 1;
                    this.fetchOrders();
                }
            },
            currentPage(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.fetchOrders();
                }
            },
            pageSize(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.fetchOrders();
                }
            }
        },
        methods: {
            fetchOrders() {
                this.user = JSON.parse(localStorage.getItem('user'));
                const userId = this.user && this.user.roleType !== 'admin' ? this.user.id : null;

                axios.get('/order?operation=findOrdersByPageAndUserId', {
                    params: {
                        keyword: this.searchKeyword,
                        pageNum: this.currentPage,
                        pageSize: this.pageSize,
                        userId: userId
                    }
                }).then(response => {
                    const {code, data} = response.data;
                    if (code === 200) {
                        this.orders = data.data.map(order => {
                            order.seats = JSON.parse(order.status).seats.map(seat => `${seat.row}排${seat.col}号`);
                            order.status = JSON.parse(order.status);
                            return order;
                        });
                        this.totalOrders = data.total;
                    } else {
                        this.$message.error('获取订单列表失败');
                    }
                }).catch(error => {
                    console.error('获取订单列表失败:', error);
                    this.$message.error('获取订单列表失败');
                });
            },
            handleDelete(order) {
                this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post('/order?operation=deleteOrder&id=' + order.id)
                        .then(response => {
                            if (response.data.code === 200) {
                                this.$message.success('订单删除成功');
                                this.fetchOrders();
                            } else {
                                this.$message.error('订单删除失败');
                            }
                        })
                        .catch(error => {
                            console.error('订单删除失败:', error);
                            this.$message.error('订单删除失败');
                        });
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            },
            handlePay(order) {
                this.$confirm('确认支付该订单吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post('/order?operation=updateOrder', {
                        id: order.id,
                        status: JSON.stringify({
                            seats: order.status.seats,
                            paymentStatus: 'paid'
                        })
                    }).then(response => {
                        if (response.data.code === 200) {
                            this.$message.success('支付成功');
                            this.fetchOrders();
                        } else {
                            this.$message.error('支付失败');
                        }
                    }).catch(error => {
                        console.error('支付失败:', error);
                        this.$message.error('支付失败');
                    });
                }).catch(() => {
                    this.$message.info('已取消支付');
                });
            },
            showTicket(order) {
                this.selectedOrder = order;
                this.ticketDialogVisible = true;
            },
            printTicket() {
                const printWindow = window.open('', '_blank');
                const ticketContent = document.querySelector('.ticket-content').innerHTML;

                printWindow.document.write(`
                    <html>
                        <head>
                            <title>电影票据打印</title>
                            <style>
                                body { font-family: Arial, sans-serif; padding: 20px; }
                                .ticket-content { text-align: center; }
                                .ticket-header { font-size: 24px; margin-bottom: 20px; }
                                .ticket-info { text-align: left; margin: 10px 0; line-height: 1.8; }
                            </style>
                        </head>
                        <body>
                            ${ticketContent}
                        </body>
                    </html>
                `);

                printWindow.document.close();
                printWindow.print();
                printWindow.close();
            },
            handleSizeChange(val) {
                this.pageSize = val;
            },
            handleCurrentChange(val) {
                this.currentPage = val;
            }
        },
        mounted() {
            this.fetchOrders();
        }
    });
</script>

</body>
</html>